Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

181
Visualizações
Trying to save object in useState but getting undefined or Array []

I have been trying to save the result of an API call with a usestate. but I am trying to avoid an interface since the response will be very large and may vary on a case by case basis.

how would I go about saving this response?

const DetailPage = ({navigation, route}) => {
    const [recipeData2, setRecipeData2] = useState();
    const [loading, setLoading] = useState(true);
    const [key, setKey] = useState('APIKEY IS HERE');

    const {id} = route.params;

    console.log(id)

    const getRecipeData2 = async() => {
        setLoading(true);


        const url = 'https://api.spoonacular.com/recipes/' + id + '/information?apiKey=' + key + '&includeNutrition=false';
        axios.get(url).then(function (response) {
            setRecipeData2(response.data);
            console.log(response.data);
            console.log(recipeData2);
        }).catch(function (error) {
            console.log(error);

            if(error) {
                console.log('error')
            }
        });

        setLoading(false);
    }

    useEffect(() => {
        getRecipeData2();
    }, [])

    return (
        <View>
          <Text></Text>  
        </View>
    )
}

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

What it seems is you need to provide initial value to your useState and also you are not setting your loader until your promise is completed for that you can use .finally() block of promise. So doing these things can fix the issue for you. Here's what needs to be done -

const DetailPage = ({ navigation, route }) => {
    const [recipeData2, setRecipeData2] = useState([]);
    const [loading, setLoading] = useState(true);
    const [key, setKey] = useState('APIKEY IS HERE');

    const { id } = route.params;

    const getRecipeData2 = async () => {
        setLoading(true);
        const url = 'https://api.spoonacular.com/recipes/' + id + '/information?apiKey=' + key + '&includeNutrition=false';
        axios.get(url).then(function (response) {
            setRecipeData2(response.data);
        }).catch(function (error) {
            if (error) console.log('error')
        }).finally(function () {
            setLoading(false);
        })
    }

    useEffect(() => {
        getRecipeData2();
    }, [])

    return (
        <View>
            {
                recipeData2.map((data, index) => {
                    return <Text key={ index.toString() }> { data.title } </Text>
                })
            }
        </View>
    )
}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda